//
//  RegisterViewController.m
//  金融
//
//  Created by Apple on 2017/9/27.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "RegisterViewController.h"
#import "ProtocolViewController.h"

#define MAX_STARWORDS_LENGTH 6

@interface RegisterViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIButton    *  yanBtn;

@end

@implementation RegisterViewController

- (UIButton *)yanBtn
{
    if (!_yanBtn) {
        _yanBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        [_yanBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_yanBtn setTitleColor:RedColor forState:UIControlStateNormal];
        _yanBtn.contentMode = UIViewContentModeCenter;
        _yanBtn.titleLabel.font = FONT(15);
        [_yanBtn addTarget:self action:@selector(clickYanBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _yanBtn;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
    [self setNavBar];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickTap)];
    [self.view addGestureRecognizer:tap];
    self.yanTF.rightView = self.yanBtn;
    self.yanTF.keyboardType = UIKeyboardTypeNumberPad;
    self.yanTF.rightViewMode = UITextFieldViewModeAlways;
    self.passTF.returnKeyType = UIReturnKeyDone;
    self.phoneTF.delegate = self;
    self.yanTF.delegate = self;
    self.passTF.delegate = self;
    self.passTF.secureTextEntry = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification" object: self.yanTF];

    [self AttProtcolBtn];
}
- (void)setNavBar
{
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = @"注册";
}
- (void)clickTap
{
    [self.phoneTF resignFirstResponder];
    [self.passTF resignFirstResponder];
    [self.yanTF resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.phoneTF) {
        [self.yanTF becomeFirstResponder];
    }else if(textField == self.yanTF){
        [self.passTF resignFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return YES;
}
- (void)AttProtcolBtn
{
    NSString * str = @"点击'立即注册',即同意《注册协议》";
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    [attrStr addAttribute:NSForegroundColorAttributeName
                    value:UIColorRGB(0x929292)
                    range:NSMakeRange(0, 12)];
    
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:12]
                    range:NSMakeRange(0, attrStr.length)];
    
    [attrStr addAttribute:NSForegroundColorAttributeName
                    value:UIColorRGB(0x2772ff)
                    range:NSMakeRange(12,attrStr.length - 12)];

    [self.ProtoclBtn setAttributedTitle:attrStr forState:UIControlStateNormal];
}
-(void)textFieldEditChanged:(NSNotification *)obj
{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > MAX_STARWORDS_LENGTH)
            {
                textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > MAX_STARWORDS_LENGTH)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

- (void)clickYanBtn
{
    if (self.phoneTF.text.length != 11) {
        [MyObject failedPrompt1:@"手机号码不正确"];
        return;
    }
    WeakSelf
    [HttpRequest postWithURLString:HOST(@"common/sms/send") parameters:@{@"phone":self.phoneTF.text,@"type":[NSNumber numberWithInteger:1]} showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        [MyObject failedPrompt1:responseObject[@"message"]];
        if ([responseObject[@"code"] integerValue] == 20000) {
            __block NSInteger timeout = 60; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        weakSelf.yanBtn.backgroundColor = [UIColor whiteColor];
                        [weakSelf.yanBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                        [weakSelf.yanBtn setTitleColor:TITLEColor forState:UIControlStateNormal];
                        weakSelf.yanBtn.userInteractionEnabled = YES;
                    });
                }else{
                    int seconds = timeout % 61;
                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [weakSelf.yanBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                        [weakSelf.yanBtn setTitleColor:UIColorRGB(0x929292) forState:UIControlStateNormal];
                        weakSelf.yanBtn.userInteractionEnabled = NO;
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);
        }
    } failure:^(NSError * _Nullable error) {
        NSLog(@"%@",error);
    }login:^(BOOL isLogin) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)clickRegister:(id)sender {
    
    if (self.phoneTF.text.length != 11 || self.passTF.text.length == 0 || self.yanTF.text.length == 0) {
        return;
    }

    WeakSelf
    [HttpRequest postWithURLString:HOST(@"auth/register/phone") parameters:@{@"phone":self.phoneTF.text,@"password":self.passTF.text,@"smsCode":self.yanTF.text} showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        [MyObject failedPrompt1:responseObject[@"message"]];
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            [HFUser saveToken:responseObject[@"data"][@"token"]];
            [HFUser rememberUserID:responseObject[@"data"][@"userId"]];
            [HFUser saveRefreshToken:responseObject[@"data"][@"refreshToken"]];
            [HFUser rememberUsername:responseObject[@"data"][@"username"]];
            [HFUser rememberNickName:responseObject[@"data"][@"nickName"]];
            [weakSelf saveIcon:responseObject[@"data"][@"avatar"]];
            [[NSNotificationCenter defaultCenter] postNotificationName:LOGINSUCCESS object:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //设置界面的按钮显示 根据自己需求设置
            weakSelf.yanBtn.backgroundColor = [UIColor whiteColor];
            [weakSelf.yanBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [weakSelf.yanBtn setTitleColor:TITLEColor forState:UIControlStateNormal];
            weakSelf.yanBtn.userInteractionEnabled = YES;
        });
    } failure:^(NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //设置界面的按钮显示 根据自己需求设置
            weakSelf.yanBtn.backgroundColor = [UIColor whiteColor];
            [weakSelf.yanBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [weakSelf.yanBtn setTitleColor:TITLEColor forState:UIControlStateNormal];
            weakSelf.yanBtn.userInteractionEnabled = YES;
        });
    }login:^(BOOL isLogin) {
        NSLog(@"111");
    }];
}
- (void)saveIcon:(NSString *)image
{
    WeakSelf
    dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL); // 创建GCD线程队列
    dispatch_async(xrQueue, ^{
        // 异步下载图片
        UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:image]]];
        // 主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *path_document = NSHomeDirectory();
            //设置一个图片的存储路径
            NSString *imagePath = [path_document stringByAppendingString:@"/Documents/icon.png"];
            //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
            [UIImagePNGRepresentation(img) writeToFile:imagePath atomically:YES];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
    });
}

- (IBAction)clickProtcolAction:(id)sender {
    ProtocolViewController * pc = [[ProtocolViewController alloc] init];
    [self.navigationController pushViewController:pc animated:YES];
}
@end
